<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="bom编号" label-width="55" prop="bomSn">
        <el-input
          v-model="queryParams.bomSn"
          placeholder="请输入bom编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="$route.query.proBomId==null"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:bom:add']"
        >新增BOM</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:deliver:export']"
        >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="bomList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="序号" align="center" prop="number" />
      <el-table-column label="bom编号" align="center" prop="bomSn" />
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:bom:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:bom:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加BOM管理对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="90%" append-to-body >
      <el-divider class="bom_divider"></el-divider><!--分割线-->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="table-layout: auto">
        <el-form-item v-if="this.$route.query.productId==null" label="产品" prop="proId">
          <el-select v-model="form.proId" placeholder="请选择" style="width:30%" @change="handleProChange">
            <el-option
                v-for="item in productOptions"
                :key="item.id"
                :label="`${item.proName}/${item.proSn}`"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="产品" prop="proId">
          <span>{{form.proName + '/' + form.proSn}}</span>
        </el-form-item>
        <el-row>
            <el-col :span="8">
              <el-form-item label="产品名称:" prop="proName">
                  <span>{{ form.proName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品编码:" prop="proSn">
                <span>{{ form.proSn }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品类型:" prop="proType">
                <span>{{ myMap.get(form.proType) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" style="width:30%"/>
        </el-form-item>
        <el-form-item label="物料列表" >
          <el-button style="margin-bottom: 10px;" type="primary" @click="bommtradd(count)">添 加</el-button>
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
              <el-table-column label="物料名称" align="center" prop="matName">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.matSn" filterable placeholder="请选择"
                             @change="(option) => mtrchang(option, scope.$index)">
                    <el-option v-for="item in matOptions" :key="item.matSn" :label="item.matName" :value="item.matSn">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="物料编码" align="center" prop="matSn"/>
              <el-table-column label="物料参考价格" align="center" prop="matPrice">
                <template slot-scope="scope">
                  {{ scope.row.matPrice==undefined?'0元':scope.row.matPrice+'元' }}
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input-number id="inputNumber" v-model:value="scope.row.matNum" :min="0" :precision="2"/>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="bommtradd(scope.$index)"
                             v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="bommtrdel(scope.$index)"
                             v-hasPermi="['mes:proinfo:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-card>
        </el-form-item>
        <div style="display: flex; justify-content: center; margin-top: 10px;">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-form>
    </el-drawer>
    <!-- 修改BOM管理对话框 -->
    <el-drawer :title="title2" :visible.sync="open2" size="90%" append-to-body>
      <el-divider></el-divider><!--分割线-->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称:" prop="proName">
              <span>{{ form.proName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编码:" prop="proName">
              <span>{{ form.proSn }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品类型:" prop="proName">
              <span>{{ myMap.get(form.proType) }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="bom编号" prop="bomSn">
          <el-input v-model="form.bomSn" placeholder="请输入bom编号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-row>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="创建者" prop="bomSn">-->
<!--              <el-input v-model="form.createBy" placeholder="请输入创建者" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="创建时间" prop="bomSn">-->
<!--              <el-input v-model="form.createdTime" placeholder="请输入创建时间" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="更新者" prop="bomSn">-->
<!--              <el-input v-model="form.updatedBy" placeholder="请输入更新者" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="6">-->
<!--            <el-form-item label="更新时间" prop="bomSn">-->
<!--              <el-input v-model="form.updatedTime" placeholder="请输入更新时间" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-form-item label="物料列表" >
        <el-button style="margin-bottom: 10px;" type="primary" @click="bommtradd1(count)">添 加</el-button>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="物料名称" align="center" prop="proName">
              <template slot-scope="scope">
                <el-select v-model="scope.row.proMateriel.matSn" filterable placeholder="请选择"
                           @change="(option) => mtrchang1(option, scope.$index)">
                  <el-option v-for="item in matOptions" :key="item.id" :label="item.matName" :value="item.matSn">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="物料编码" align="center" prop="matSn">
              <template slot-scope="scope">
                {{ scope.row.proMateriel.matSn }}
              </template>
            </el-table-column>
            <el-table-column label="物料参考价格" align="center" prop="cost">
              <template slot-scope="scope">
                {{ scope.row.proMateriel.matPrice==undefined?'0元':scope.row.proMateriel.matPrice+'元' }}
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="scope.row.matNum" :min="0" :precision="2"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="bommtradd1(scope.$index)"
                           v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="bommtrdel(scope.$index)"
                           v-hasPermi="['mes:proinfo:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-card>
        </el-form-item>
        <div style="display: flex; justify-content: center; margin-top: 10px;">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, getBomMat,updateBom} from "@/api/mes/bom";
import {listPro_design, getPro_design} from "@/api/mes/pro_design";
import {listMateriel} from "@/api/mes/materiel";
import item from "@/layout/components/Sidebar/Item";

export default {
  name: "Bom",
  data() {
    return {
      //计数
      count: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM管理表格数据
      bomList: [],
      // 添加弹出层标题
      title: "",
      // 查看弹出层标题
      title1: "",
      // 修改弹出层标题
      title2: "",
      // 是否显示新增弹出层
      open: false,
      // 是否显示修改弹出层
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomSn: null,
      },
      // 查询参数
      queryParams1: {
        // pageNum: 1,
        // pageSize: 10000,
        proName: null,
        proType: null,
      },
      // 查询参数
      queryParamsMaterile: {
        // pageNum: 1,
        // pageSize: 10000,
        matSn: null,
        matName: null,
      },
      // 表单参数
      form: {},
      // 产品选项
      productOptions: [],
      // 物料选项
      matOptions: [],
      //定义Map
      myMap: new Map(),
      // 表单校验
      rules: {

      }
    };
  },
  created() {
    this.getList();
    this.getMateriel();
    this.myMap.set( 0,'成品');
    this.myMap.set( 1,'半成品');
    this.myMap.set( 2,'原材料');
  },
  watch: {
    '$route.query.productId' (to, from) { //监听路由是否变化
      if(this.$route.path == '/pro/bom'){//仅在当前页面生效
        if(to != from){
          // this.queryParams.taskId = to;
          this.getList();//重新加载数据
        }
      }
    }
  },
  methods: {
    /**
     * 下拉框改变
     * @param {选项值} option
     */
    mtrchang(option, index) {
      let ss = this.matOptions.find(item => item.matSn == option)
      this.form.mtrs[index].matName = ss.matName
      this.form.mtrs[index].matSn= ss.matSn
      this.form.mtrs[index].matPrice = ss.matPrice
      this.form.mtrs[index].matNum = ss.matNum
      this.form.mtrs[index].matId = ss.id
      console.log(this.matOptions,"物料数组")
    },

    mtrchang1(option, index) {
      let ss = this.matOptions.find(item => item.matSn == option)
      this.form.mtrs[index].matName = ss.matName
      this.form.mtrs[index].proMateriel.matSn= ss.matSn
      this.form.mtrs[index].proMateriel.matPrice = ss.matPrice
      this.form.mtrs[index].proMateriel.matNum = ss.matNum
      this.form.mtrs[index].matId = ss.id
      console.log(this.form,"物料数组1")
    },

    /**
     * 删除物料
     * @param {下标} index
     */
    bommtrdel(index) {
      this.form.mtrs.splice(index, 1);
      console.log(index,"!!!!!!!!!!!!!!!!!!!!!!")
      this.count=this.count-1
    },

    /**
     * 添加物料
     * @param {下标} index
     * @param {行数据} row
     */
    bommtradd(index) {
      console.log(this.form)
      if (index != undefined) {
        this.form.mtrs.splice(index + 1, 0,
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            matId: null,
            houId: null,
            matName: null,
            matSn: null,
            matPrice: 0,
            proMateriel:{},
            matNum: 0
          })
      } else {
        this.form.mtrs.push(
           {
             createBy: "",
             createTime: "",
             updateBy: "",
             updateTime: null,
             remark: null,
             matId: null,
             houId: null,
             matName: null,
             matSn: null,
             matPrice: 0,
             matNum: 0,
             proMateriel:{},
           })
      }
      this.count=this.count+1
    },

    bommtradd1(index) {
      console.log("3165469418569",this.form.mtrs)
      if (index != undefined) {
        this.form.mtrs.splice(index + 1, 0,
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            matId: null,
            id:null,
            houId: null,
            proMateriel:{
              matSn: null,
              matName: null,
              matPrice: 0,
            },
            matNum: 0
          })
      } else {
        this.form.mtrs.push(
          {
            createBy: "",
            createTime: "",
            updateBy: "",
            updateTime: null,
            remark: null,
            matId: null,
            id:null,
            houId: null,
            proMateriel:{
              matSn: null,
              matName: null,
              matPrice: 0,
            },
            matNum: 0
          })
      }
      this.count=this.count+1
    },


    handleProChange() {
      if (this.form.proId != null) {
        // 根据 form.proId 找到对应的存址
        this.form.proId = parseInt(this.form.proId);
        const selectedProduct = this.productOptions.find(option => option.id === this.form.proId);
        if (selectedProduct) {
          console.log(selectedProduct, "handleProChange!")
          // 更新其他输入框的值
          this.form.proName = selectedProduct.proName;
          this.form.proSn = selectedProduct.proSn;
          this.form.proType = selectedProduct.proType;
        }
      }
      else {
        // 根据 form.id(bom表id) 找到对应产品的存址
        this.form.id = parseInt(this.form.id);
        const selectedProduct = this.productOptions.find(option => option.proBomId === this.form.id);
        if (selectedProduct) {
          console.log(selectedProduct, "handleProChange!!")
          // 更新其他输入框的值
          this.form.proId = selectedProduct.id;
          this.form.proName = selectedProduct.proName;
          this.form.proSn = selectedProduct.proSn;
          this.form.proType = selectedProduct.proType;
        }
      }
    },
    //获取产品表数据
    getProduct(){
        listPro_design(this.queryParams1,{ refresh: true }).then(response =>{
        this.productOptions = response.rows;
        console.log('产品选项信息!!!:',this.productOptions);
          // 在此处执行后续的代码
          if (this.$route.query.productId) {
            this.form.proId = this.$route.query.productId;
            this.handleProChange();
            console.log(this.form.proId, "productId-------------");
          }
          else{
            const proBomId = 'proBomId';
            this.productOptions = this.productOptions.filter(item=>!item[proBomId])
          }
        })
    },

    //获取物料表数据
    getMateriel(){
      // this.productOptions=this.getProducts()
      listMateriel(this.queryParamsMaterile).then(response =>{
        this.matOptions = response.rows;
        console.log('物料选项信息:',this.matOptions);
      })
    },

    /** 查询BOM管理列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then(response => {
        this.bomList = response.rows;
        console.log("afdadfa",this.$route.query.proBomId)
        if(this.$route.query.proBomId!=null){
          const proBomId = parseInt(this.$route.query.proBomId)
          this.bomList=this.bomList.filter(item=>item.id===proBomId)
        }
        this.total = response.total;
        this.calculateIndex()
        this.loading = false;
      });

    },
    /** 列表编号 */
    calculateIndex() {
      this.bomList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bomSn: null,
        remark: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        mtrs: [],
        proId: null,
        proName: null,
        proType: null,
        proSn:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增BOM";
      this.getProduct();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBom(id).then(response => {
        this.form = response.data;
        // this.count= 0;
        // this.open2 = true;
        // this.handleProChange();
        // this.title2 = "修改BOM";
      });
      getBomMat(id).then(response => {
        this.form.mtrs = response;
        this.count= response.length;
        this.open2 = true;
        this.handleProChange();
        this.title2 = "修改BOM";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form,"submitForm")
      console.log(this.form.mtrs)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open2=false;
              this.getList();
            });
          } else {
            addBom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // submitForm1() {
    //   console.log(this.form,"submitForm114514")
    //   console.log(this.form.mtrs)
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateBomMat(this.form.mtrs).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const bomSn = row.bomSn || this.bomSn;
      this.$modal.confirm('是否确认删除BOM编号为"' + bomSn + '"的数据项？').then(function() {
        return delBom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/bom/export', {
        ...this.queryParams
      }, `bom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
